import {
  getCoupons
} from '../../sers/coupon/coupon';
import {
  getBanners
} from '../../sers/home/home';
import drawQrcode from '/weapp.qrcode.min.js'
const app = getApp();
var wxbarcode = require('/barcode.js');
Page({
  data: {
    lbtlist: [],
    pageLoading: false,
    tittop: '0rpx',
    bgimg: '',
    lbtop: '0rpx',
    swwidth: '',
    swheight: '',
    swml: '',
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    circular: true,
    interval: 3500,
    duration: 500,
    previousMargin: -1,
    nextMargin: -1,
    isshowtit: false,
    couponList: [],
    userInfo: app.globalData.userInfo,
    isShowPop: false,
    sch: app.globalData.sh,
    spaceTag: false,
    copyrightBottom: {
      bottom: '0rpx',
      position: 'fixed',
      bottom1: '30rpx',
    },
    jsheight: 0,
    fixviewht: 0,
    fixviewhtstr: '0rpx',
    jsheightstr: '0rpx',
    zxFlag: false,
    qrCodeSrc: '',
    tempPath: '',
    tempPath1: '',
    showcode: false,
    qrCodeValue: '3126159601149442220',
    isQrCodeVisible: false,
  },
  onLoad(options) {
    console.log("获取用户信息")
    console.log(options)
    if (options.fromShare == '1' && options.couponId) {
      const couponId = options.couponId;
      // 使用 navigateTo 跳转到商品页，保留首页在栈底
      wx.navigateTo({
        url: `/pages/coupon/buycoupon/index?couponId=${couponId}`
      });
    }
    // 否则正常显示首页
    console.log(wx.getStorageSync('cache_user_info'))
    this.getData()
    if (this.data.userInfo == null) {
      this.data.userInfo = wx.getStorageSync('cache_user_info')
      if (this.data.userInfo == '没有找到会员') {
        wx.clearStorageSync();
        // app.user_auth_login(this, 'user_auth_back_event', '');
      }
      // this.data.userInfo=wx.getStorageSync('userInfo')
    }
    if (options.op && options.op === 'exithmb') {
      this.setData({
        userInfo: null
      });
    }
    let rcode;
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      rcode = scene;
      // wx.setStorageSync("index_rcode", rcode);
      app.globalData.rcode = rcode;
    }
    this.init();
  },
  onClose() {
    this.setData({
      zxFlag: false
    });
  },
  //判断优惠券是否被领取
  getCardDis() {
    let giftParame = wx.getStorageSync('get_gif_parme')
    let data = {
      couponCode: giftParame.splitIdCoupon
    }
    wx.request({
      url: app.get_request_url("checkCoupon", "coupons"),
      method: "POST",
      data: data,
      dataType: "json",
      success: res => {
        console.log("首页获取用户是否领取优惠券！")
        console.log(res)
        if (res.data.code == 0) {
          if (res.data.data.status == 0) {
            wx.showModal({
              title: '',
              content: '前往领取好友赠送券！',
              confirmText: '确认',
              cancelText: '暂不',
              success: (result) => {
                if (result.confirm) {
                  console.log("跳转")
                  let cunponCard = `/pages/coupon/claimCoupon/index?couponId=${giftParame.couponId}&num=${giftParame.num}&splitIdCoupon=${giftParame.splitIdCoupon}&status=${true}`
                  wx.navigateTo({
                    url: cunponCard
                  });
                }
              }
            });
          }
        } else {
          // app.showToast(res.data.msg);
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        app.showToast("服务器请求出错");
      }
    });
    // }

  },
  getgift() {
    let giftUrl = wx.getStorageSync('get_gif_url')
    let giftParame = wx.getStorageSync('get_gif_status')
    console.log(giftUrl)
    console.log(giftParame)
    if (giftParame) {
      wx.showModal({
        title: '',
        content: '前往领取好友赠送券！',
        confirmText: '确认',
        cancelText: '暂不',
        success: (result) => {
          if (result.confirm) {
            console.log("跳转")
            let cunponCard = `/pages/coupon/claimCoupon/index?couponId=${giftParame.couponId}&num=${giftParame.num}&splitIdCoupon=${giftParame.splitIdCoupon}&status=${true}`
            wx.navigateTo({
              url: cunponCard
            });
          }
        }
      });
    }
  },
  onPullDownRefresh() {
    if (this.data.isShowPop) {
      wx.stopPullDownRefresh();
      this.setData({
        pageLoading: false
      });
    } else {
      this.init();
    }
    wx.stopPullDownRefresh();
  },

  init() {
    this.loadHomePage();
  },

  loadHomePage() {
    this.setData({
      pageLoading: true
    });
    //  this.data.userInfo = wx.getStorageSync('userInfo');
    let sw = app.globalData.sw;
    let rate = 750 / sw;
    let lbw = (sw - 20) * rate + 'rpx';
    let nlbh = ((sw - 20) * 140 / 351 * rate).toFixed(2);
    let lbh = nlbh + 'rpx';
    let nml = 10 * rate;
    let ml = nml + 'rpx';
    if (this.data.userInfo == null || this.data.userInfo == '') {
      this.data.fixviewht = parseFloat(app.globalData.lbtop) + parseFloat(nlbh) + parseFloat(nml);
      this.data.jsheight = parseFloat(app.globalData.lbtop) + parseFloat(nlbh) + parseFloat(nml) + 75;
    } else {
      if (app.globalData.isWindows) {
        this.data.fixviewht = parseFloat(nlbh) + parseFloat(nml) + 145;
        this.data.jsheight = parseFloat(nlbh) + parseFloat(nml) + 215;
      } else {
        this.data.fixviewht = parseFloat(app.globalData.lbtop) + parseFloat(nlbh) + parseFloat(nml) + 145;
        this.data.jsheight = parseFloat(app.globalData.lbtop) + parseFloat(nlbh) + parseFloat(nml) + 215;
      }
    }
    this.setData({
      tittop: app.globalData.tittop + 'rpx',
      lbtop: app.globalData.lbtop + 'rpx',
      swwidth: lbw,
      swml: ml,
      swheight: lbh,
      isshowtit: app.globalData.isWindows ? false : true,
      jsheight: this.data.jsheight,
      fixviewhtstr: this.data.fixviewht + 'rpx',
      jsheightstr: this.data.jsheight + 'rpx'
    });
    getBanners().then(imgList => {
      console.log(imgList);
      this.setData({
        lbtlist: imgList.data.data.banner_list,
        pageLoading: false,
        bgimg: imgList.data.data.banner_list[0].images_url,
      });
    }).catch(error => {
      console.log(error);
    });
  },
  getData() {
    //获取会员数据
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobileTemp;
    console.log(user)
    if (user != null) {
      mobileTemp = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobileTemp = app.globalData.userInfo.mobile
      }
    }
    if (mobileTemp != null) {
      let that = this;
      wx.request({
        url: app.get_request_url("member", "user"),
        method: "POST",
        data: {
          'mobile': mobileTemp,
        },
        dataType: "json",
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: res => {
          wx.stopPullDownRefresh();
          console.log("11111111111111111111111111111")
          if (res.data.code == 0) {
            var data = res.data.data;
            this.setData({
              userInfo: data,
            });
            console.log("asdasdasd")
            this.getCardDis()
            //不是会员弹出提示注册 
            if (this.data.userInfo == '没有找到会员') {
              this.setData({
                userInfo: null,
              });
              // wx.navigateTo({
              //   url: "/pages/usercenter/updateMember/index"
              // });
            } else {
              wx.setStorageSync('cache_user_info', data);
              drawQrcode({
                width: 250,
                height: 250,
                foreground: '#404040',
                canvasId: 'myQrcode',
                text: this.data.userInfo.memberQrCode
              })
              this.barc('barcode', this.data.userInfo.memberQrCode, 600, 200);
              this.getCouponList(mobileTemp);
            }
          }
        },
        fail: () => {
          wx.stopPullDownRefresh();
          app.showToast("服务器请求出错");
        }
      });
    } else {
      // if(app.globalData.isFirst == 1){
      //   app.globalData.isFirst = 0;
      //   this.setData({
      //     isShowPop:true
      //   });
      // }
      this.getCouponList('18888888888');
    }
  },

  swipchg: function (e) {
    let cur_img = this.data.lbtlist[e.detail.current];
    this.setData({
      bgimg: cur_img.images_url
    });
  },

  loadCouponList(mobileTemp) {
    getCoupons(mobileTemp).then(couponList => {
      if (couponList == null || couponList == "underdfine") {
        couponList == [];
      }
      let cnt = couponList.length;
      let facthjs = this.data.jsheight + cnt * 200;
      let tmpWinh = app.globalData.winHeight * (750 / app.globalData.sw);
      if (tmpWinh - facthjs > 62) {
        var cb = {
          bottom: '0rpx',
          position: 'fixed',
          bottom1: '30rpx',
        };
        this.setData({
          copyrightBottom: cb
        });
      } else {
        var cb = {
          bottom: '',
          position: '',
          bottom: '',
        };
        this.setData({
          copyrightBottom: cb
        });
      }

      this.getCouponList(mobileTemp)
      //  this.setData({
      //    couponList: couponList
      //  });
    }).catch(error => {
      console.log(error);
    });
  },

  getCouponList(mobileTemp) {
    wx.request({
      url: app.get_request_url("getcouponlist", "coupons"),
      method: "POST",
      data: {
        mobile: mobileTemp
      },
      dataType: "json",
      success: res => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        if (res.data.code == 0) {
          var data = res.data.data;
          console.log("kkkk")
          console.log(data)
          // const data = myArray.slice(0, 2); // 从索引0开始，到索引2（不包括2）
          if (data != null) {
            for (var i = 0; i < data.length; ++i) {
              var temp = data[i].remark.replace(/\\n/g, '');
              data[i].remark = temp;
              if (data[i].couponType == 3) {
                data[i].money = data[i].money + '张';
              }
              // let result = str.slice(0, 2);
              data[i].beginTime = data[i].beginTime.substring(5, 11);
              data[i].endTime = data[i].endTime.substring(5, 11);
            }
          }

          this.setData({
            couponList: data || [],
          });

          if (data == null || data == "underdfine") {
            data = [];
          }
          let cnt = data.length;
          let facthjs = this.data.jsheight + cnt * 200;
          let tmpWinh = app.globalData.winHeight * (750 / app.globalData.sw);
          if (tmpWinh - facthjs > 62) {
            var cb = {
              bottom: '0rpx',
              position: 'fixed',
              bottom1: '30rpx'
            };
            this.setData({
              copyrightBottom: cb
            });
          } else {
            var cb = {
              bottom: '',
              position: '',
              bottom1: ''
            };
            this.setData({
              copyrightBottom: cb
            });
          }

        } else {
          app.showToast(res.data.msg);
        }
      },

      fail: () => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        app.showToast("服务器请求出错");
      }
    });
  },

  barc(id, code, width, height) {
    wxbarcode.code128(wx.createCanvasContext(id), code, this.convert_length(width), this.convert_length(height))
  },
  convert_length(length) {
    return Math.round(wx.getSystemInfoSync().windowWidth * length / 1000);
  },
  // 点击券未登录提示
  buyCouponHandle(e) {
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobileTemp;
    if (user != null) {
      mobileTemp = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobileTemp = app.globalData.userInfo.mobile
      }
    }
    if (mobileTemp == null) {
      let id = e.detail.id;
      //   this.setData({
      //     isShowPop:true
      //   });
      wx.navigateTo({
        url: '/pages/coupon/buycoupon/index?couponId=' + id,
      });
    } else {
      let id = e.detail.id;
      var couponTemp;
      for (var i = 0; i < this.data.couponList.length; ++i) {
        if (this.data.couponList[i].couponId == id) {
          couponTemp = this.data.couponList[i];
        }
      }
      if (couponTemp.type == 2) {
        if (this.data.userInfo.point < couponTemp.value) {
          app.showToast('积分不够，请积分足够时再试试。。。')
        } else {
          wx.navigateTo({
            url: '/pages/coupon/buycoupon/index?couponId=' + id,
          });
        }
      } else {
        wx.navigateTo({
          url: '/pages/coupon/buycoupon/index?couponId=' + id,
        });
      }
    }
  },
  toLogin() {
    console.log('进入toLogin');
    const userInfo = {
      avatarUrl: '../../images/tx.png',
      cardNo: '1234567890',
      mobile: '13988888888',
      memberLevel: '银卡',
      point: 2000,
      memberName: '大美人',
      memberSex: '女',
      birthday: '2000-09-01',
      address: '女儿国丽质省天香市倾国街No1',
      memberQrCode: '3126565767676766'
    };
    app.globalData.userInfo = userInfo;
    wx.setStorageSync('userInfo', userInfo);
    this.setData({
      userInfo: userInfo
    });

  },

  confirmQrCode(e) {
    // 打开会员码
    this.getuserInfo()
    if (this.data.userInfo != null && this.data.userInfo.memberQrCode != null && this.data.userInfo.memberQrCode != '') {
      this.setData({
        zxFlag: true
      });
    }
  },
  getuserInfo() {
    var userT = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobileTempT;
    if (userT != null) {
      mobileTempT = userT.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobileTempT = app.globalData.userInfo.mobile
      }
    }
    wx.request({
      url: app.get_request_url("member", "user"),
      method: "POST",
      data: {
        'mobile': mobileTempT,
      },
      dataType: "json",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        //   wx.stopPullDownRefresh();
        if (res.data.code == 0) {
          var data = res.data.data;
          this.setData({
            userInfo: data,
          });
          //不是会员弹出提示注册 
          if (this.data.userInfo == '没有找到会员') {
            wx.navigateTo({
              url: "/pages/usercenter/updateMember/index"
            });
          } else {
            wx.setStorageSync('cache_user_info', data);
            drawQrcode({
              width: 250,
              height: 250,
              foreground: '#404040',
              canvasId: 'myQrcode',
              text: this.data.userInfo.memberQrCode
            })
            this.barc('barcode', this.data.userInfo.memberQrCode, 600, 200);
            console.log(this.data.userInfo)
            //   this.getCouponList(mobileTemp);
          }
        }
      },
      fail: () => {
        wx.stopPullDownRefresh();
        app.showToast("服务器请求出错");
      }
    })
  },

  confirmAuth(e) {
    //console.log(e);
    var mobileTemp;
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    if (user != null) {
      mobileTemp = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobileTemp = app.globalData.userInfo.mobile
      }
    }
    if (mobileTemp == null) {
      this.setData({
        isShowPop: true
      });
    }
  },
  modalCancel(e) {
    console.log('进入modalCancel');
    this.setData({
      isShowPop: false
    });
  },
  modalConfirm(e) {
    console.log('进入modalConfirm');
    this.setData({
      isShowPop: false
    });
    // this.toLogin();
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobileTemp;
    if (user != null) {
      mobileTemp = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobileTemp = app.globalData.userInfo.mobile
      }
    }
    if (mobileTemp == null) {
      wx.showModal({
        title: '温馨提示',
        content: '授权用户信息',
        confirmText: '确认',
        cancelText: '暂不',
        success: (result) => {
          if (result.confirm) {
            wx.navigateTo({
              url: "/pages/login/login"
            });
          }
        }
      });
    }

  },

  toLinkYsZy(e) {
    console.log("打开隐私指引");
    wx.openPrivacyContract({
      success: res => {
        console.log('openPrivacyContract success')
      },
      fail: res => {
        console.error('openPrivacyContract fail', res)
      }
    })
  },

  // onPageScroll: function(e) {
  //   // 页面滚动时触发
  //   console.log('页面滚动,当前滚动位置:', e.scrollTop);
  // }

  onShareAppMessage: function () {

  },

})